What is JWT?
🔹 What is JWT?
JWT (JSON Web Token) is a secure, compact way to transmit information between two parties (like client ↔ server).
-
Server generates a JWT token after login.
-
Client stores it (usually in localStorage/sessionStorage).
-
For each API request, client sends the token in the Authorization header.
-
Server validates the token before giving access.
🔹 Why use JWT in WebAPI?
✅ Stateless (no session stored in server memory)
✅ Works well in distributed/microservices systems
✅ Compact and secure (signed with secret key)
✅ Easy to pass in HTTP headers
🔹 JWT Token Structure
A JWT has 3 parts (separated by .):
-
Header – algorithm & token type
-
Payload – claims (user info, roles, expiry)
-
Signature – hash of header+payload+secret
Example:
🔹 Steps in .NET WebAPI with JWT
1. Install Package
2. Add JWT Settings in appsettings.json
3. Configure JWT in Program.cs
4. Create a Login Controller to Generate Token
5. Protect API Endpoints with [Authorize]
🔹 Flow
-
Client calls
POST /api/auth/loginwith username & password. -
Server responds with JWT token.
-
Client saves token.
-
For protected APIs, client sends:
-
Server validates token → If valid, access granted.
🔹 Example Request in Postman
POST /api/auth/login
Body (JSON):
Response:
✅ Now you have JWT Authentication working in .NET WebAPI.
-
Easy to integrate with Angular/React or even mobile apps.
-
Secure since the token is signed and can include roles/claims.
Comments
Post a Comment